import axios, { AxiosResponse } from "axios"
import dayjs from "dayjs"
import { createDBClient } from "../view"
import { BaseMongoClient } from "../controller/mongodb"
import { DailyReportInterface, FaucetInterface, FiveMinitesReportInterface, HourlyReportInterface, LastPaidInterface } from "../model"
import { getTime, initDataDaily, initDataFaucet, initDataFive, initDataHour, initDataLastPaid } from "../utils"

/**
 * 五分钟添加一次
 * @param fiveClient five_report集合
 * @param lastClient last_paid集合
 * @param faucetClient faucet集合
 */
export async function insertFiveData(config: any) {
    /**
    * 格式化时间
    */
    const clients = await createDBClient(config.config)
    const { now_min } = getTime()
    let res: any
    res = await axios.get("https://faucetpay.io/api/listv1/faucetlist")

    const data = res.data.list_data.normal
    for (const i in data) {
        for (const n in data[i]) {
            let item = data[i][n]
            //查询faucet集合是否存在指定数据
            let faucet = await getOrinsertFaucet(clients.faucetClient, item)
            //处理last_paid集合
            await streamLastPaid(item, clients.lastClient, now_min, faucet)
            const insertData = initDataFive(item, faucet._id, now_min)
            await clients.fiveClient.insert(insertData)
        }
    }
    console.log("five_report集合添加成功！")

}


//每小时添加
export async function insertHourData(config: any) {
    const clients = await createDBClient(config.config)

    let hour_data = await initDataHour(clients)

    if (hour_data.length == 0) {
        return
    }

    await clients.hourClient.insertMany(hour_data)
    console.log("hour_report集合添加成功！")
}


//每天添加
export async function insertDailyData(config: any) {
    const clients = await createDBClient(config.config)

    const daily_data = await initDataDaily(clients)
    await clients.dailyClient.insertMany(daily_data)
    console.log("daily_report集合添加成功！")
}



/**
* operationTime：新增数据或者paid_today改变时 的日期
* 根据主键查数据。
*     没有数据： 添加，退出
*     有数据 ： 数据库取paid_today与接口数据比较
*                  改变了：  last_paid_mins 固定5
*                  没改变： 当前时间的毫秒值减去数据库operationTime的毫秒值  除以6W 得到分钟即为支付间隔  
* @param data 接口数据
* @param lastClient last_paid集合
* @param insertTime 插入时间
* @param faucetDatas faucet集合数据
* @returns 
*/
export async function streamLastPaid(data: any, lastClient: BaseMongoClient<LastPaidInterface>, insertTime: number, faucetDatas: FaucetInterface): Promise<LastPaidInterface> {

    //根据主键查询数据
    const last_paid = await lastClient.getOne({ condition: { "faucet_id": faucetDatas._id } })

    /**
    * 不存在数据就insert数据，并且返回insert的数据。
    */
    if (!last_paid) {
        let lastPaid: LastPaidInterface = initDataLastPaid(data, insertTime, faucetDatas._id)
        await lastClient.insert(lastPaid)
        return lastPaid
    } else {
        const api_paid_today = data.paid_today
        const db_paid_today = last_paid.paid_today
        let last_paid_mins = 5;

        if (api_paid_today == db_paid_today) {
            const last_paid_operationTime = last_paid.operationTime
            const now_insertTime = insertTime
            last_paid_mins = (now_insertTime - Number(last_paid_operationTime)) / 60
            insertTime = Number(last_paid.operationTime)
        }
        await lastClient.updateOne({ "_id": last_paid._id, "faucet_id": faucetDatas._id, "paid_today": api_paid_today, "operationTime": String(insertTime), "last_paid_mins": last_paid_mins })
        return last_paid
    }

}


/**
 * 获取数据或者添加数据
 * 
 * @param faucetClient 
 * @param item 
 * @returns 
 */
async function getOrinsertFaucet(faucetClient: BaseMongoClient<FaucetInterface>, item: any) {
    let faucet: FaucetInterface;

    const faucet_data = await faucetClient.getOne({ condition: { "id": item.id, "currency": item.currency } });

    if (!faucet_data) {
        faucet = initDataFaucet(item);
        await faucetClient.insert(faucet)
        return faucet;
    }
    return faucet_data;
}


